package com.company.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.RestUtil;
import com.company.project.common.websocket.WebSocket;
import com.company.project.pojo.Rest;
import com.company.project.pojo.ServiceCode;
import com.company.project.common.utils.JwtUtil;
import com.company.project.pojo.FilePojo;
import com.company.project.pojo.configFile.ConfigFile;
import com.company.project.pojo.contradiction.*;
import com.company.project.pojo.contradictionRecord.ContradictionRecord;
import com.company.project.pojo.contradictionRecord.ContradictionRecordInfoVO;
import com.company.project.pojo.institution.Institution;
import com.company.project.pojo.roleVillage.RoleVillageDTO;
import com.company.project.pojo.village.Village;
import com.company.project.service.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 矛盾 前端控制器
 * </p>
 *
 * @author 任建波
 * @since 2019-08-09
 */
@Api(value = "矛盾资料",tags = "矛盾资料")
@Controller
@RequestMapping("contradiction")
public class ContradictionController {

//    @Value("${file-url-prefix}")
    private String fileUrlPrefix;

    @Autowired
    IConfigFileService iConfigFileService;
    @Autowired
    private IRoleVillageService iRoleVillageService;
    @Autowired
    private IContradictionService iContradictionService;
    @Autowired
    private IContradictionRecordService iContradictionRecordService;
    @Autowired
    private IInstitutionService iInstitutionService;
    @Autowired
    private IVillageService  iVillageService;
    @Autowired
    HttpServletRequest request;

    @ApiOperation(value = "获取矛盾资料列表")
    @RequestMapping(value = "getContradictionListPage", method = RequestMethod.GET)
    @ResponseBody
    public Rest getContradictionListPage(Integer currentPage, String keyword, Integer status, Integer isPush, String startTime, String endTime){
        IPage page = iContradictionService.getContradictionListPage(new Page(currentPage, 10), keyword, status, isPush, startTime, endTime);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , page);
    }

    @ApiOperation(value = "获取登录人提交的矛盾资料列表")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "页码", name = "currentPage", required = true, dataType = "integer"),
        @ApiImplicitParam(paramType="query", value = "每页多少条数据", name = "pageSize", required = true, dataType = "integer"),
        @ApiImplicitParam(paramType="query", value = "状态： 0：待提交，1：待解决，2已解决，null：全部", name = "status", dataType = "integer"),
        @ApiImplicitParam(paramType="query", value = "开始时间", name = "startTime", dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "结束时间", name = "endTime", dataType = "String"),
    })
    @RequestMapping(value = "getContradictionListPageByInputUserId", method = RequestMethod.GET)
    @ResponseBody
    public Rest getContradictionListPageByInputUserId(Integer currentPage, Integer pageSize, Integer status, String startTime, String endTime){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);

        IPage<ContradictionDTO> pageInfo = iContradictionService.getContradictionListPageByInputUserId(new Page(currentPage, pageSize), user_id, status, startTime, endTime);

        List<ContradictionAppVOTable> contradictionAppVOTableList = new ArrayList<>();

        for (ContradictionDTO contradictionDTO: pageInfo.getRecords()){
            ContradictionAppVOTable contradictionAppVOTable = new ContradictionAppVOTable();
            BeanUtils.copyProperties(contradictionDTO, contradictionAppVOTable);

            contradictionAppVOTableList.add(contradictionAppVOTable);
        }
        IPage<ContradictionAppVOTable> newPageInfo = new Page<>();
        newPageInfo.setRecords(contradictionAppVOTableList);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , newPageInfo);
    }

    @ApiOperation(value = "根据id获取矛盾资料", notes = "根据id获取矛盾资料")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "矛盾资料id", name = "id", required = true, dataType = "Integer")
    })
    @RequestMapping(value = "getContradictionById", method = RequestMethod.GET)
    @ResponseBody
    public Rest<ContradictionInfoVO> getContradictionById(Integer id){
        ConfigFile configFile = iConfigFileService.getById(1);
        fileUrlPrefix = configFile.getFileUrlPrefix();

        Contradiction contradiction = iContradictionService.getById(id);

        ContradictionInfoVO contradictionInfoVO = new ContradictionInfoVO();
        BeanUtils.copyProperties(contradiction, contradictionInfoVO);
        contradictionInfoVO.setImg(toFile(contradiction.getImgUrl()));
        contradictionInfoVO.setVideo(toFile(contradiction.getVideoUrl()));
        contradictionInfoVO.setAudio(toFile(contradiction.getAudioUrl()));
        contradictionInfoVO.setFile(toFile(contradiction.getFileUrl()));

        Village village = iVillageService.getById(contradiction.getVillageId());
        Institution institution = iInstitutionService.getById(village.getInstitutionId());
        contradictionInfoVO.setVillageName(village.getName());
        contradictionInfoVO.setInstitutionId(village.getInstitutionId());
        contradictionInfoVO.setInstitutionName(institution.getName());

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , contradictionInfoVO);
    }

    @ApiOperation(value = "查询推送给单位的矛盾资料", notes = "查询推送给单位的矛盾资料")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "页码", name = "currentPage", required = true, dataType = "integer"),
        @ApiImplicitParam(paramType="query", value = "状态", name = "status", dataType = "integer")
    })
    @RequestMapping(value = "getContradictionListByHandleInstitutionId", method = RequestMethod.GET)
    @ResponseBody
    public Rest<IPage<ContradictionTableVO>> getContradictionListByHandleInstitutionId(Integer currentPage, Integer status){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer role_id = claims.get("role_id", Integer.class);
        Integer institutionId = claims.get("institution_id", Integer.class);

        List<RoleVillageDTO> roleVillageDTOList = iRoleVillageService.getRoleVillageListByRoleId(role_id);

        IPage<ContradictionDTO> pageInfo = iContradictionService.getContradictionListByHandleInstitutionId(new Page(currentPage, 10), roleVillageDTOList, institutionId, role_id, status);

        List<ContradictionTableVO> contradictionTableVOList = new ArrayList<>();

        for (ContradictionDTO contradictionDTO: pageInfo.getRecords()){
            ContradictionTableVO contradictionTableVO = new ContradictionTableVO();
            BeanUtils.copyProperties(contradictionDTO, contradictionTableVO);

            contradictionTableVOList.add(contradictionTableVO);
        }
        IPage<ContradictionTableVO> newPageInfo = new Page<>();
        newPageInfo.setRecords(contradictionTableVOList);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , newPageInfo);
    }

    @ApiOperation(value = "根据角色id查询矛盾资料", notes = "根据角色id查询矛盾资料")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "页码", name = "currentPage", required = true, dataType = "integer"),
        @ApiImplicitParam(paramType="query", value = "状态", name = "status", dataType = "integer"),
        @ApiImplicitParam(paramType="query", value = "开始时间", name = "startTime", dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "结束时间", name = "endTime", dataType = "String")
    })
    @RequestMapping(value = "getContradictionListByRoleId", method = RequestMethod.GET)
    @ResponseBody
    public Rest<IPage<ContradictionAppVOTable>> getContradictionListByRoleId(Integer currentPage, Integer status, String startTime, String endTime){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer role_id = claims.get("role_id", Integer.class);
        Integer institutionId = claims.get("institution_id", Integer.class);

        List<RoleVillageDTO> roleVillageDTOList = iRoleVillageService.getRoleVillageListByRoleId(role_id);

        IPage<ContradictionDTO> pageInfo = iContradictionService.getContradictionListByRoleId(new Page(currentPage, 10), roleVillageDTOList, institutionId, role_id, status, startTime, endTime);

        List<ContradictionAppVOTable> contradictionAppVOTableList = new ArrayList<>();

        for (ContradictionDTO contradictionDTO: pageInfo.getRecords()){
            ContradictionAppVOTable contradictionAppVOTable = new ContradictionAppVOTable();
            BeanUtils.copyProperties(contradictionDTO, contradictionAppVOTable);

            contradictionAppVOTableList.add(contradictionAppVOTable);
        }
        IPage<ContradictionAppVOTable> newPageInfo = new Page<>();
        newPageInfo.setRecords(contradictionAppVOTableList);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , newPageInfo);
    }

    @ApiOperation(value = "查询待提交的矛盾资料", notes = "查询待提交的矛盾资料")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "页码", name = "currentPage", required = true, dataType = "integer")
    })
    @RequestMapping(value = "getToBeSubmittedContradictionList", method = RequestMethod.GET)
    @ResponseBody
    public Rest<IPage<ContradictionAppVOTable>> getToBeSubmittedContradictionList(Integer currentPage){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);
        QueryWrapper<Contradiction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("input_user_id", user_id);
        queryWrapper.eq("status", 0);

        IPage<ContradictionDTO> pageInfo = iContradictionService.getToBeSubmittedContradictionList(new Page(currentPage, 10), user_id);

        List<ContradictionAppVOTable> contradictionAppVOTableList = new ArrayList<>();

        for (ContradictionDTO contradictionDTO: pageInfo.getRecords()){
            ContradictionAppVOTable contradictionAppVOTable = new ContradictionAppVOTable();
            BeanUtils.copyProperties(contradictionDTO, contradictionAppVOTable);

            contradictionAppVOTableList.add(contradictionAppVOTable);
        }
        IPage<ContradictionAppVOTable> newPageInfo = new Page<>();
        newPageInfo.setRecords(contradictionAppVOTableList);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , newPageInfo);
    }

    private FilePojo[] toFile(String str){
        if(str != null && !str.equals("")){
            String[] strs = str.split("@@");
            FilePojo[] filePojos = new FilePojo[strs.length];

            for (int i=0; i<strs.length ; i++){
                FilePojo filePojo = new FilePojo();
                filePojo.setUrl(fileUrlPrefix + strs[i]);
                filePojo.setName(strs[i].split("@_@")[1]);

                filePojos[i] = filePojo;
            }

            return filePojos;
        }else {
            return null;
        }
    }

    @ApiOperation(value = "添加矛盾资料", notes="")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "addContradiction", method = RequestMethod.POST)
    @ResponseBody
    public Rest addContradiction(@RequestBody  @Valid ContradictionForm contradictionForm) throws IOException {
        Contradiction contradiction = new Contradiction();
        BeanUtils.copyProperties(contradictionForm, contradiction);

        contradiction.setImgUrl(fileToSting(contradictionForm.getImg()));
        contradiction.setVideoUrl(fileToSting(contradictionForm.getVideo()));
        contradiction.setAudioUrl(fileToSting(contradictionForm.getAudio()));
        contradiction.setFileUrl(fileToSting(contradictionForm.getFile()));

        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);
        Integer institution_id = claims.get("institution_id", Integer.class);

        contradiction.setInputUserId(user_id);
        contradiction.setInputInstitutionId(institution_id);

        iContradictionService.save(contradiction);

        // 9999:两委      9998:书记     9997: 乡贤
        if(contradictionForm.getSolveUserId() != null && !contradiction.getStatus().equals(0)){
//            ContradictionRecord contradictionRecord = new ContradictionRecord();
//            contradictionRecord.setContradictionId(contradiction.getId());
//            contradictionRecord.setInputUserId(user_id);
//            contradictionRecord.setInstitutionId(institution_id);
//            contradictionRecord.setStatus(1);
//            contradictionRecord.setHandleUserId(contradictionForm.getSolveUserId());
//            contradictionRecord.setHandleTime(new Date());
//            iContradictionRecordService.save(contradictionRecord);
            contradiction.setSolveUserId(contradictionForm.getSolveUserId());
            contradiction.setSolveTime(new Date());
//            contradiction.setStatus(2);
        }

        WebSocket.sendInfo("addContradiction");

        return RestUtil.rest(ServiceCode.CODE_200, "成功" );
    }

    @ApiOperation(value = "修改矛盾资料", notes="")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "updateContradiction", method = RequestMethod.POST)
    @ResponseBody
    public Rest updateContradiction(@RequestBody ContradictionForm contradictionForm){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);
        Integer institution_id = claims.get("institution_id", Integer.class);

        Contradiction contradiction = new Contradiction();
        BeanUtils.copyProperties(contradictionForm, contradiction);

        contradiction.setImgUrl(fileToSting(contradictionForm.getImg()));
        contradiction.setVideoUrl(fileToSting(contradictionForm.getVideo()));
        contradiction.setAudioUrl(fileToSting(contradictionForm.getAudio()));
        contradiction.setFileUrl(fileToSting(contradictionForm.getFile()));

        // 9999:两委      9998:书记     9997: 乡贤
        if(contradictionForm.getSolveUserId() != null && !contradiction.getStatus().equals(0)){
//            ContradictionRecord contradictionRecord = new ContradictionRecord();
//            contradictionRecord.setContradictionId(contradiction.getId());
//            contradictionRecord.setInputUserId(user_id);
//            contradictionRecord.setInstitutionId(institution_id);
//            contradictionRecord.setStatus(1);
//            contradictionRecord.setHandleUserId(contradictionForm.getSolveUserId());
//            contradictionRecord.setHandleTime(new Date());
//            iContradictionRecordService.save(contradictionRecord);
            contradiction.setSolveUserId(contradictionForm.getSolveUserId());
            contradiction.setSolveTime(new Date());
//            contradiction.setStatus(2);
        }

        iContradictionService.updateById(contradiction);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" );
    }

    private String fileToSting(FilePojo[] filePojos){
        if(filePojos != null && filePojos.length > 0){
            String str = "";
            for (int i=0; i<filePojos.length ; i++){
                if(i < filePojos.length - 1){
                    str += filePojos[i].getUrl() + "@@";
                }else if(i == filePojos.length - 1){
                    str += filePojos[i].getUrl();
                }
            }
            return str;
        }else {
            return null;
        }
    }

    @ApiOperation(value = "解决矛盾资料", notes="")
    @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String")
    @RequestMapping(value = "solveContradiction", method = RequestMethod.POST)
    @ResponseBody
    public Rest solveContradiction(Integer id){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);

//        QueryWrapper<ContradictionRecord> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("is_delete", 0);
//        queryWrapper.eq("contradiction_id", id);
//        queryWrapper.orderByDesc("handle_time");
//        List<ContradictionRecord> contradictionRecordList = iContradictionRecordService.list(queryWrapper);
//        if(contradictionRecordList.size() < 1){
//            return RestUtil.rest(ServiceCode.CODE_403, "还没有推送记录，不能设置为解决" );
//        } else {
//            ContradictionRecord contradictionRecord = contradictionRecordList.get(0);
//            if(!contradictionRecord.getStatus().equals(1)){
//                return RestUtil.rest(ServiceCode.CODE_403, "该问题还未解决，不能设置为解决" );
//            }
//        }

        Contradiction contradiction = iContradictionService.getById(id);
        if(contradiction.getSolveUserId() == null){
            return RestUtil.rest(ServiceCode.CODE_403, "该问题还没有人解决，不能设置为解决" );
        } else {
            contradiction.setId(id);
            contradiction.setStatus(2);

            iContradictionService.updateById(contradiction);
        }

        return RestUtil.rest(ServiceCode.CODE_200, "成功" );
    }

    @ApiOperation(value = "获取解决方案", notes="")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", value = "矛盾资料id", name = "contradictionId", required = true, dataType = "Integer"),
    })
    @RequestMapping(value = "getSolution", method = RequestMethod.POST)
    @ResponseBody
    public Rest<ContradictionRecordInfoVO> getSolution(Integer contradictionId){
        QueryWrapper<ContradictionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contradiction_id", contradictionId);
        queryWrapper.eq("status", 1);

        ContradictionRecord contradictionRecord = iContradictionRecordService.getOne(queryWrapper);
        if (contradictionRecord != null){
            ConfigFile configFile = iConfigFileService.getById(1);
            fileUrlPrefix = configFile.getFileUrlPrefix();

            ContradictionRecordInfoVO contradictionRecordInfoVO = new ContradictionRecordInfoVO();
            if(contradictionRecord != null){
                BeanUtils.copyProperties(contradictionRecord, contradictionRecordInfoVO);
                contradictionRecordInfoVO.setImg(toFile(contradictionRecord.getImgUrl()));
                contradictionRecordInfoVO.setVideo(toFile(contradictionRecord.getVideoUrl()));
                contradictionRecordInfoVO.setAudio(toFile(contradictionRecord.getAudioUrl()));
                contradictionRecordInfoVO.setFile(toFile(contradictionRecord.getFileUrl()));
            }

            return RestUtil.rest(ServiceCode.CODE_200, "成功" , contradictionRecordInfoVO);
        } else {
            return RestUtil.rest(ServiceCode.CODE_200, "无解决方案");
        }
    }
}

